﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Globalization;

namespace WowGuildSite.Armory
{
    internal class ArmoryXmlDocument
    {
        internal delegate       string      ContentRetrievalDelegate();

        private ContentRetrievalDelegate    retriever;
        private XmlDocument                 document;

        internal XmlDocument                Document
        {
            get
            {
                if (document == null)
                {
                    string content = retriever();

                    if (string.IsNullOrEmpty(content))
                    {
                        throw new ArmoryException("The requested entity does not exist.");
                    }

                    document = new XmlDocument();
                    document.LoadXml(content);
                }
                return document;
            }
        }

        internal IList<XmlElement>          GetElements(string path)
        {
            List<XmlElement>    result  = new List<XmlElement>();
            XmlNodeList         nodes   = Document.SelectNodes(path);

            foreach (XmlElement e in nodes)
            {
                result.Add(e);
            }

            return result;
        }

        internal XmlElement                 GetElement(string path)
        {
            return Document.SelectSingleNode(path) as XmlElement;
        }

        internal string                     GetElementText(string path )
        {
            return ArmoryXmlUtility.GetElementText(GetElement(path)); 
        }

        internal int                        GetElementInt(string path)
        {
            return ArmoryXmlUtility.GetElementInt(GetElement(path));
        }

        internal decimal                    GetElementDecimal(string path)
        {
            return ArmoryXmlUtility.GetElementDecimal(GetElement(path));
        }

        internal XmlAttribute               GetAttribute(string path)
        {
            return Document.SelectSingleNode(path) as XmlAttribute;
        }

        internal string                     GetAttributeText(string path)
        {
            return ArmoryXmlUtility.GetAttributeText(GetAttribute(path));
        }

        internal int                        GetAttributeInt(string path)
        {
            return ArmoryXmlUtility.GetAttributeInt(GetAttribute(path));
        }

        internal decimal                    GetAttributeDecimal(string path)
        {
            return ArmoryXmlUtility.GetAttributeDecimal(GetAttribute(path));
        }

        internal ArmoryXmlDocument( ContentRetrievalDelegate retriever )
        {
            if (retriever == null )
            {
                throw new ArgumentNullException("retriever");
            }
            this.retriever = retriever;
        }
    }
}
